<template>
  <view class="page">
    <scroll-view class="scroll-view" scroll-y scroll-with-animation :scroll-top="top"
                 @refresherrefresh="onRefresherrefresh"
                 @refresherpulling="refresherpulling"
                 refresher-enabled
                 :refresher-triggered="refreshing"
                 :scroll-into-view="bottomAnchor"
                 @refresherrestore="onRefresherrestore"
                 :refresher-threshold="10">
      <view style="padding: 30rpx 30rpx 240rpx;">
        <view v-if="noMoreip" class="no-more-tip">
          <text>没有更多历史消息了</text>
        </view>
        <view class="message" :class="[item.userType]" v-for="(item,index) in list" :key="index">
          <image :src="headSculptureFriend" v-if="item.userType === 'friend'" class="avatar" mode="widthFix"></image>
          <view class="content" v-if="item.messageType === 'image'">
          </view>
          <view class="content" v-else>
            <view v-if="item.contentType === 2">
              <image :src="item.content" style="width: 40vw;" :show-menu-by-longpress="true" mode="widthFix"></image>
            </view>
            <view v-else>{{ item.content }}</view>
          </view>
          <image :src="headSculpture" v-if="item.userType === 'self'" class="avatar" mode="widthFix"></image>


        </view>
      </view>
      <view id="bottomAnchor" style="height: 1px;"></view>
    </scroll-view>
    <view class="tool">
      <input type="text" v-model="content" class="input" @focus="handleFocus"
             @blur="handleBlur" @confirm="send" />
      <button @click="send" class="send-btn">发送</button>
      <view style="height: 35px; width: 35px; border-radius: 5px; text-align: center; margin-left: 3px;  background: #f5f5f5" @click="openDialog" v-if="orderPayStatus > 1">
        <TnIcon name="reply" bold size="20px" />
        <view style="font-size: 8px">外部群</view>
      </view>
    </view>
    <TnPopup ref="popup" v-model="showPopup" position="center">
      <view class="popup-content">
        <view class="popup-header">
          <image :show-menu-by-longpress="true" :src="groupText.groupChatUrl" style="width: 300px; height: 500px" alt="" />
          <view class="popup-title" style="text-align: center; padding: 10px; color: #999999">{{groupText.groupChatScript}}</view>
        </view>
      </view>
    </TnPopup>
  </view>
</template>

<script setup lang="ts">
import {ref, onUnmounted, nextTick, onMounted} from 'vue';
import {UniWebSocketClient} from "@/utils/socket";
import {onHide, onLoad, onShow} from "@dcloudio/uni-app";
import {
  createGroupChatApi,
  messagesListApi,
  saveConversationApi,
  updateMessageStatusByTimestampApi
} from "@/api/message";
import TnPopup from '@tuniao/tnui-vue3-uniapp/components/popup/src/popup.vue'
import {connectGoEasy, disconnectGoEasy, initGoEasy, publishMessage, subscribeChannel} from "@/utils/socketV2";
const content = ref("");
const top = ref(0);
const messageId = ref("");
const bottomAnchor = ref('');

onLoad(async (params: any) => {
  list.value = [];
  // const pages = getCurrentPages();
  // const currentPage: any = pages[pages.length - 1];
  // const params = currentPage.options;
  initChat(params);
})

interface UserInfo {
  headSculpture: string
  openId: string
}

interface Params {
  userId: string
  headSculpture?: string
  projectId?: string
  conversationId?: string
  orderPayStatus: number;
}

interface MessageData {
  content: string,
  userType: string,
  avatar?: string,
  messageType?: string,
  time?: string,
}

const previewImage = () => {
  uni.previewImage({
// 需要预览的图片链接列表
    urls: [groupText.value.groupChatUrl],
// 当前显示图片的链接
    current: groupText.value.groupChatUrl,
// 图片指示器样式
    indicator: 'default',
// 是否可循环预览
    loop: false,
// 长按图片显示操作菜单
// longPressActions: {
// itemList: ['发送给朋友', '保存到相册']
// },
    success: res => {
      console.log('previewImage res', res);
    },
    fail: err => {
      console.log('previewImage err', err);
    }
  });
}

const headSculpture = ref<string>("")
const headSculptureFriend = ref<string>("")
const userId = ref<string>("")
const conversationId = ref<string>("")
const list = ref<MessageData[]>([])
let wsClient: UniWebSocketClient | null = null
const noMoreip = ref<boolean>(false)
const orderPayStatus = ref(0);
async function initChat(params: Params) {
  try {
    // 1. 获取用户信息
    const userInfo: UserInfo = uni.getStorageSync("userInfo")
    if (!userInfo?.openId) throw new Error("用户信息缺失")

    headSculpture.value = userInfo.headSculpture
    userId.value = params.userId
    headSculptureFriend.value = params.headSculpture || ""
    orderPayStatus.value = params?.orderPayStatus || 0;

    // 2. 初始化会话 ID
    if (params.projectId) {
      const res = await saveConversationApi({
        customerOpenid: params.userId,
        projectId: params.projectId
      })
      conversationId.value = res?.data || ""
    } else if (params.conversationId) {
      conversationId.value = params.conversationId
    }

    // 3. 初始化 WebSocket
    // wsClient = new UniWebSocketClient(
    //     wsUrl,
    //     userInfo.openId
    // )

    // wsClient.onMessage((msg: string) => {
    //   try {
    //     console.log("📨 页面收到消息:", msg)
    //     const msgJson = JSON.parse(msg)
    //     list.value.push({
    //       content: msgJson.msg,
    //       userType: "friend",
    //       avatar: ""
    //     })
    //   } catch (err) {
    //     console.error("消息解析失败:", err)
    //   }
    // })

    await initGoEasy("BC-0910ecd4492c4356a43654a8b4af49c3", userId.value);
    connectGoEasy("user-001", { nickname: "Neo" });
    subscribeChannel(conversationId.value + userInfo.openId, (msg) => {
      // messages.value.push({ content: msg.content });
      try {
        const msgJson = JSON.parse(msg.content)
        list.value.push({
          content: msgJson.msg,
          userType: "friend",
          avatar: "",
          time: msg.time
        })
      } catch (err) {
        console.error("消息解析失败:", err)
      }
    });

    // 4. 加载历史消息并滚动
    await getHishTory(conversationId.value)
    scrollToBottom()
  } catch (err) {
    console.error("聊天初始化失败:", err)
  }
}

const showPopup = ref(false);
const groupText = ref({ groupChatScript: "", groupChatUrl: ""});
const openDialog = async () => {
  const res = await createGroupChatApi({conversationId: conversationId.value});
  if (res?.code === 200) {

    groupText.value = res?.data || {};
    if (groupText.value.groupChatUrl) {
      showPopup.value = true;
      const userInfo = uni.getStorageSync("userInfo");
      publishMessage(conversationId.value + userId.value, JSON.stringify({
        type: "single",
        msg: groupText.value.groupChatUrl,
        contentType: 2,
        to: userId.value, // 接受者
        conversationId: conversationId.value, // 发送者
        senderId: userInfo.openId,
      }));
      list.value.push({
        content: groupText.value.groupChatUrl,
        userType: 'self',
        contentType: 2
      })
      publishMessage(conversationId.value + userId.value, JSON.stringify({
        type: "single",
        msg: groupText.value.groupChatScript,
        to: userId.value, // 接受者
        conversationId: conversationId.value, // 发送者
        senderId: userInfo.openId,
      }));
      list.value.push({
        content: groupText.value.groupChatScript,
        userType: 'self',
      })
      scrollToBottom();
    } else {
      uni.showToast({
        title: res?.msg || "客户未付定金，不能创建外部群",
        icon: "none"
      })
    }
  } else {
    uni.showToast({
      title: "创建外部群失败，请联系客服",
      icon: "none"
    })
  }
}


interface MessageItem {
  content: string
  senderId: string
  messageId: string
}
const getHishTory = async (conversationId: string, lastId = "") => {
  const res = await messagesListApi(conversationId, lastId)
  const userInfo = uni.getStorageSync("userInfo")

  if (res?.code === 200 && Array.isArray(res.data)) {
    const messages = res.data.reverse() as MessageItem[]

    // 1. 将消息映射成 UI 需要的格式
    const formatted = messages.map(msg => ({
      content: msg.content,
      userType: userInfo.openId === msg.senderId ? 'self' : 'friend',
      avatar: '',
      contentType: msg.contentType,
      messageId: msg.messageId,
    }))

    // 2. 逆序插入历史记录
    list.value.unshift(...formatted)

    // 3. 记录最后一条消息的 ID
    const lastMessage = messages.at(-1)
    if (lastMessage) {
      messageId.value = lastMessage.messageId
    }

    if (lastId && messages.length === 0) {
      noMoreip.value = true;
    } else {
      noMoreip.value = false
    }
  }
}
const send = async () => {
  const text = content.value.trim()
  if (!text) return // 防止发送空消息

  // 1. 先在本地添加消息
  list.value.push({
    content: text,
    userType: 'self',
  })

  // 2. 读取本地用户信息
  const userInfo = uni.getStorageSync("userInfo") as { openId?: string }
  if (!userInfo?.openId) {
    console.error("无法获取 openId，消息未发送")
    return
  }

  // 3. 构造消息体
  const message = {
    type: "single",
    msg: text,
    to: userId.value, // 接受者
    conversationId: conversationId.value, // 发送者
    senderId: userInfo.openId,
  }

  // 4. 发送消息（WebSocket 存在才发送）
  // if (wsClient) {
  //   wsClient.send(JSON.stringify(message))
  // } else {
  //   console.error("WebSocket 未连接，消息未发送")
  // }
  publishMessage(conversationId.value + userId.value, JSON.stringify(message));

  // 5. 清空输入框并滚动到底部
  content.value = ""
  scrollToBottom()
}
const scrollToBottom = () => {
  top.value = list.value.length * 1000
}

onUnmounted(() => {
  disconnectGoEasy();
  const time = list.value[list.value.length - 1]?.time || "";
  if (time) {
    updateMessageStatusByTimestampApi({
      conversationId: conversationId.value,
      timestamp: time
    })
  }

})

onHide(() => {
  disconnectGoEasy();
})

const refreshing = ref(false);
const onRefresherrefresh = (e: any) => {
  getHishTory(conversationId.value, list.value[0]?.messageId || "")
  nextTick(() => {
    refreshing.value = false // ✅ 正确终止刷新动画
  })
  setTimeout(() => {
    refreshing.value = false // ✅ 正确终止刷新动画
  }, 2000)
  return true;
}
const onRefresherrestore = () => {
  return false
}

const refresherpulling = () => {
  refreshing.value = true
}

const handleFocus = () => {
  // nextTick(() => {
  //   top.value = 999999999; // 滚到最底部
  // });
};

const handleBlur = () => {
  // nextTick(() => {
  //   top.value = 999999999; // 恢复滚动到底部
  // });
};
</script>

<style lang="scss" scoped>
.scroll-view {
  /* #ifdef H5 */
  height: calc(100vh - 44px);
  /* #endif */
  /* #ifndef H5 */
  height: 100vh;
  /* #endif */
  background: #eee;
  box-sizing: border-box;
}
.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30rpx;

  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 10rpx;
    margin-right: 30rpx;
  }
  .content {
    min-height: 80rpx;
    max-width: 60vw;
    box-sizing: border-box;
    font-size: 28rpx;
    line-height: 1.3;
    padding: 20rpx;
    border-radius: 10rpx;
    background: #fff;
    word-break: break-all;
    image {
      width: 200rpx;
    }
  }
  &.self {
    justify-content: flex-end;
    .avatar {
      margin: 0 0 0 30rpx;
    }
    .content {
      background: #4B7BF5;
      color: #FFFFFF;
      position: relative;
      &::after {
        position: absolute;
        content: '';
        width: 0;
        height: 0;
        border: 16rpx solid transparent;
        border-left: 16rpx solid #4B7BF5;
        right: -28rpx;
        top: 24rpx;
      }
    }
  }
  &.friend {
    .content {
      position: relative;
      &::after {
        position: absolute;
        content: '';
        width: 0;
        height: 0;
        border: 16rpx solid transparent;
        border-right: 16rpx solid #fff;
        left: -28rpx;
        top: 24rpx;
      }
    }
  }
}

.tool {
  position: fixed;
  width: 100%;
  min-height: 130rpx;
  left: 0;
  bottom: 0;
  background: #fff;
  display: flex;
  align-items: flex-start;
  box-sizing: border-box;
  padding: 20rpx 24rpx 30rpx 40rpx;
  padding-bottom: calc(20rpx + constant(safe-area-inset-bottom)/2) !important;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom)/2) !important;
  .input {
    background: #eee;
    border-radius: 10rpx;
    height: 70rpx;
    margin-right: 10rpx;
    flex: 1;
    padding: 0 20rpx;
    box-sizing: border-box;
    font-size: 28rpx;
  }
  .thumb {
    width: 64rpx;
  }
  .send-btn {
    height: 70rpx;
    line-height: 70rpx;
  }
}
.no-more-tip {
  display: flex;
  justify-content: center;
  align-items: center;

  color: #9CA3AF;
  font-size: 24rpx;
  margin: 15rpx 0 30rpx 0;
}
</style>
